<?php

namespace App\Kuafu\Order\Model;

use App\Kuafu\Category\Model\CategoryModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Order\Service\OrderTable;
use App\Kuafu\Product\Model\Product;
use App\Library\SnowFlake\SnowFlake;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;

class OrderDetailSplitModel extends BaseModel
{
    use HasFactory, KfSoftDeletes;

//    protected $connection = 'mysqlOrder';

    public static string $tableName;
    public static string $connectionName;

    /**
     * @param $shopId
     */
    public static function suffix($shopId)
    {
        if (is_int($shopId) && $shopId < 0) {
            $shopId = 0;
        }

        self::$tableName      = OrderTable::orderDetailTableName($shopId);
        self::$connectionName = OrderDb::orderDbConnection($shopId);

        return new static;
    }

    public function getTable()
    {
        return self::$tableName ?? parent::getTable();
    }

    public function getConnectionName()
    {
        return self::$connectionName ?? parent::getConnectionName();
    }

    public function categoryRel(): HasOne
    {
        return $this->hasOne(CategoryModel::class, 'id', 'categoryId');
    }

    /**
     * 插入订单详情
     *
     * @param $data
     */
    public static function insertOrderDetail($data)
    {
        self::query()->insert($data);
    }

    /**
     * 插入订单详情
     *
     * @param $data
     */
    public static function insertOrderDetailAfterFormat($data)
    {
        $afterData = self::formatInsertData($data);

        self::query()->insert($afterData);
    }

    /**
     * 更新订单详情
     *
     * @param $orderId
     * @param $posOrderDetail
     */
    public static function updateOrderDetail($orderId, $posOrderDetail)
    {
        // 删除 原有的 订单详情
        self::query()->where('orderId', (int)$orderId)->update(['isDeleted' => 1]);
        // 新增数据
        self::query()->insert($posOrderDetail);
    }

    public static function updateOrderDetailData(array $detailIds, array $data = [])
    {
        self::query()->whereIn('id', $detailIds)->update($data);
    }

    public static function updateOrderDetailDataByOrderId(int $orderId, array $data = [])
    {
        self::query()->where('orderId', $orderId)->update($data);
    }

    public static function getListByOrderIds($orderIds)
    {
        return self::query()
                   ->where('packageDetailId', 0)
                   ->whereIn('orderId', $orderIds)
                   ->select(['productId', 'id', 'orderId', 'imageUrl'])
                   ->get();
    }

    /**
     * 整理 OrderDetail 入库/更新 数据
     *
     * @param $data
     */
    public static function formatInsertData($data)
    {
        $result = [];
        foreach ($data as $datum) {
            $result[] = [
                'id'                       => $datum['id'],
                'orderId'                  => $datum['orderId'],
                'brandId'                  => $datum['brandId'],
                'shopId'                   => $datum['shopId'],
                'productId'                => $datum['productId'],
                'type'                     => $datum['type'],
                'productName'              => $datum['productName'],
                'unit'                     => $datum['unit'],
                'num'                      => $datum['num'],
                'originalPrice'            => $datum['originalPrice'],
                'originalUnitPrice'        => $datum['originalUnitPrice'],
                'packageId'                => $datum['packageId'],
                'packageDetailId'          => $datum['packageDetailId'],
                'packageUnitNum'           => $datum['packageUnitNum'],
                'packageUnitOriginalPrice' => $datum['packageUnitOriginalPrice'],
                'packageOriginalPrice'     => $datum['packageOriginalPrice'],
                'shouldUnitPrice'          => $datum['shouldUnitPrice'],
                'payPrice'                 => $datum['payPrice'],
                'discountPrice'            => $datum['discountPrice'],
                'discountType'             => $datum['discountType'],
                'discountNum'              => $datum['discountNum'],
                'orderDiscountPrice'       => $datum['orderDiscountPrice'],
                'totalDiscountPrice'       => $datum['totalDiscountPrice'],
                'couponDiscountPrice'      => $datum['couponDiscountPrice'],
                'couponCostPrice'          => $datum['couponCostPrice'],
                'freeNum'                  => $datum['freeNum'],
                'refundNum'                => $datum['refundNum'], // TODO 不处理退菜数据
                'createdAt'                => $datum['createdAt'],
                'createdBy'                => $datum['createdBy'],
                'createdByUid'             => $datum['createdByUid'],
                'updatedAt'                => $datum['createdAt'],
                'updatedBy'                => $datum['createdBy'],
                'updatedByUid'             => $datum['createdByUid'],
                'menuId'                   => $datum['menuId'],
                'imageUrl'                 => $datum['imageUrl'],
                'categoryId'               => $datum['categoryId'],
                'categoryName'             => $datum['categoryName']
            ];
        }
        return $result;
    }

}
